package se.rkrantz.simpleraid.service.user;

import java.security.Principal;
import java.util.Set;

import org.hibernate.HibernateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import se.rkrantz.simpleraid.hibernate.dao.UserDao;
import se.rkrantz.simpleraid.hibernate.domain.User;
import se.rkrantz.simpleraid.hibernate.domain.WowCharacter;

@Service
public class UserService {
	@Autowired private UserDao userDao;
	private static final Logger logger = LoggerFactory.getLogger(UserService.class);
	
	public void addWowCharacter(Principal principal, String characterName, String characterClass, boolean isPrimary) {
		User user = userDao.findUserByUsername(principal.getName());
		WowCharacter wc = new WowCharacter();
		wc.setCharacterName(characterName);
		wc.setCharacterClass(WowCharacter.Class.valueOf(characterClass));
		user.getCharacters().add(wc);
		userDao.update(user);
	}

	public Set<WowCharacter> getWowCharacters(Principal principal) {
		User user = userDao.findUserByUsername(principal.getName());
		return user.getCharacters();
	}

	public String setPrimaryCharacter(Principal principal, String characterId) {
		User user = userDao.findUserByUsername(principal.getName());
		try {
			userDao.setPrimaryCharacter(user, characterId);
			return characterId;
		} catch (HibernateException ex) {
			logger.warn("Changing primary character failed for user {} with message {}", user.getUsername(), ex.getMessage());
			return user.getPrimaryCharacter().getCharacterId() + "";
		}
	}
}
